import config from '../config.js'

const tips = {
  1: '抱歉，出现了错误',
  2: '尼瑪個B，網絡未連接',
  200: '请求数据成功',
  1002: '找不到资源',
  3000: '该内容不存在'
}

class HTTP {
  request({
    url,
    data = {},
    method = 'GET',
    dataType = 'json'
  }) {
    return new Promise((resolve, reject) => {
      if (!config.appkey) {
        config.appkey = ''
      }
      let configUrl = ''
      if (url.indexOf('http') == -1) {
        configUrl = config.base_api_url
      } else {
        configUrl = ''
      }
       wx.request({
        url: configUrl + url,
        data: data,
        method: method,
        dataType: dataType,
        header: {
          'content-type': 'application/json;charset=UTF-8',
          'appkey': config.appkey
        },

        success: (res) => {
          //startsWith 头的截取 //endsWith    尾巴的截取
          const code = res.statusCode.toString()
          if (code.startsWith('2')) {


            if (res.data.result) {
              return resolve(res.data.result)
            } else {
              return resolve(res.data.data)
            }
            const code = res.data.code
          } else {
            reject()
            this._show_error(code)
          }
        },

        fail: (err) => {
          reject()
          this._show_error(2)
        }
      })
    })
  }

  _show_error(code) {
    wx.showToast({
      title: tips ? tips[code] : tips[1],
      icon: 'none',
      duration: 1500
    })
  }

};

export {
  HTTP
}

